package com.dfhc.pub.service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.tools.support.log.RmLogHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dfhc.ISystemConstant;
import com.dfhc.util.HttpClientUtil;
import com.dfhc.util.StringHelper;
@Service
public class ReportProxyService {
	
	@Autowired
	FileDownloadService fileDownloadService;
	
	/**
	 * 下载报表
	 * @param reportCode 报表代码
	 * @param reportType 报表类型
	 * @param businessKey 业务主键
	 * @param parameters 报表数据源参数  
	 */
	public void download(String reportCode,String reportType,String businessKey,Map<String,Object> parameters,HttpServletResponse response) {
		
        String reportUrl = RmGlobalReference.get("URL", "report_root_url");
        reportUrl = reportUrl+"/reportInstance/api/reportGenerate";
		
		String info="";
		try {			
			Map<String, Object> bodyData = new HashMap<String,Object>();
			
			bodyData.put(ISystemConstant.REPORT_CODE, reportCode);
			bodyData.put(ISystemConstant.REPORT_TYPE, reportType);
			bodyData.put(ISystemConstant.REPORT_BUSINESS_KEY, businessKey);
			bodyData.put(ISystemConstant.PARAMETERS,JSON.toJSONString(parameters));
			
			JSONObject json = new JSONObject(bodyData);
			
			info = HttpClientUtil.postReportGenerate(reportUrl, json);
			Map<String,Object> dataMap = JSON.parseObject(info); 
		    String status = (String)dataMap.get(ISystemConstant.AJAX_STATUS);
		    String byteStr =null;
		    String fileName =null;
		    byte convertBytes[]=null;
		    if(status.equals(ISystemConstant.AJAX_RESULT_SUCCESS)){
		    	byteStr = (String)dataMap.get(ISystemConstant.AJAX_BEAN);
		    	fileName = (String)dataMap.get(ISystemConstant.FILE_NAME);
		    	if(byteStr!=null){
		    		 convertBytes = Base64.decodeBase64(byteStr);
		    	}
		    	fileDownloadService.downloadStream(fileName, convertBytes, response);
		    	
		    }else{
		    	Map<String, Object> result = new HashMap<String, Object>();
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "下载报表失败!");
				response.setContentType("text/html;charset=utf-8");
				try {
					response.getWriter().print(JSONObject.toJSONString(result));
					response.getWriter().flush();
				} catch (Exception ex) {
					ex.printStackTrace();
				} 
		    }
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}		
	}
	
	
	/**
	 * 查看报表
	 * @param reportCode 报表代码
	 * @param reportType 报表类型
	 * @param businessKey 业务主键
	 * @param parameters 报表数据源参数
	 */
	public void viewReport(String reportCode,String reportType,String businessKey,Map<String,Object> parameters,HttpServletResponse response) {
		
		//获取报表项目的路径
		String reportUrl = RmGlobalReference.get("URL", "report_root_url");
        reportUrl = reportUrl+"/reportInstance/api/reportGenerate";
		
		String info="";
		try {			
			Map<String, Object> bodyData = new HashMap<String,Object>();
			
			bodyData.put(ISystemConstant.REPORT_CODE, reportCode);
			bodyData.put(ISystemConstant.REPORT_TYPE, reportType);
			bodyData.put(ISystemConstant.REPORT_BUSINESS_KEY, businessKey);
			bodyData.put(ISystemConstant.PARAMETERS,JSON.toJSONString(parameters));
			
			JSONObject json = new JSONObject(bodyData);
			
			info = HttpClientUtil.postReportGenerate(reportUrl, json);
			Map<String,Object> dataMap = JSON.parseObject(info); 
		    String status = (String)dataMap.get(ISystemConstant.AJAX_STATUS);
		    String byteStr =null;
		    String reportTypes =null;
		    byte convertBytes[]=null;
		    if(status.equals(ISystemConstant.AJAX_RESULT_SUCCESS)){
		    	byteStr = (String)dataMap.get(ISystemConstant.AJAX_BEAN);
		    	reportTypes = (String)dataMap.get(ISystemConstant.REPORT_TYPE);
		    	if(byteStr!=null){
		    		//转换成字节数组 
		    		convertBytes = Base64.decodeBase64(byteStr);
		    		 //查看报表的格式类型(html,pdf)
		    		 if(reportTypes.equals(ISystemConstant.DICTIONARY_REPORT_TYPE_02)){
		    			//写流文件到前端浏览器   
			 		    OutputStream out = response.getOutputStream();   
			 		    response.setHeader("Content-Type", "text/html");
			 			response.setContentType("application/pdf");//输出pdf
			 			//response.setContentType("text/html; charset=UTF-8");//输出html
			 			try {   
			 			    out.write(convertBytes);  
			 		        out.flush();
			 		    } catch (IOException e) {   
			 		    	RmLogHelper.error(getClass(), StringHelper.exceptionToString(e));
			 		    	throw e;
			 		    } finally {   
			 		      if(out!=null){
			 		    	  out.close();
			 		      }
			 			} 
		    		 }else if(reportTypes.equals(ISystemConstant.DICTIONARY_REPORT_TYPE_01)){
		    			//写流文件到前端浏览器   
			 		    OutputStream out = response.getOutputStream();   
			 		    response.setHeader("Content-Type", "text/html");
			 			//response.setContentType("application/pdf");//输出pdf
			 			response.setContentType("text/html; charset=UTF-8");//输出html
			 			try {   
			 			    out.write(convertBytes);  
			 		        out.flush();
			 		    } catch (IOException e) {   
			 		    	RmLogHelper.error(getClass(), StringHelper.exceptionToString(e));
			 		    	throw e;
			 		    } finally {   
			 		      if(out!=null){
			 		    	  out.close();
			 		      }
			 			} 
		    		 }else if(reportTypes.equals(ISystemConstant.DICTIONARY_REPORT_TYPE_03)){
		    			 //查看excel报错
		    			 throw new RuntimeException("不支持xls格式文件的查看!");
		    		 }
		    		
		    	}
		    }else if(status.equals(ISystemConstant.AJAX_RESULT_FAIL)){
		    	
		    	 Map<String, Object> result = new HashMap<String, Object>();//
					result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
					result.put(ISystemConstant.AJAX_MESSAGE, "报表编码重复!");
					response.setContentType("text/html;charset=utf-8");
					try {
						response.getWriter().print(JSONObject.toJSONString(result));
						response.getWriter().flush();
					} catch (Exception ex) {
						ex.printStackTrace();
					} 
		    }
		     
		    
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}		
	}
	
}
